<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\model\InReceiptDetail;
use app\home\severs\InReceiptSever;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class InReceipt
 * @package app\home\controller
 * 入库单
 */
class InReceipt extends BaseController
{
    protected $table = 'in_receipt';
    protected $title = '入库单';
    private $sessionKey='pageInReceipt';
    protected $businessType = [
    ];//业务类型
protected $cacheKey='inreceiptPrintOrdernum';
public function __construct(App $app)
{
    parent::__construct($app);
    $this->businessType=config('config.inReceiptType');
}

    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param = $this->param;
        if (request()->isAjax()) {

            $where[] = ['i.status', '>', -1];
            foreach (['i_type', 'i_id', 'i_status'] as $i) {
                if (isset($param[$i]) && $param[$i]) {
                    $k = str_replace('_', '.', $i);
                    $where[] = [$k, '=', $param[$i]];
                }
            }
            foreach (['p_name', 'u_name','i_orderNum'] as $i) {
                if (isset($param[$i]) && $param[$i]) {
                    $k = str_replace('_', '.', $i);
                    $where[] = [$k, 'like', '%' . $param[$i] . '%'];
                }
            }
            if (isset($param['i_incomTime']) && $param['i_incomTime']) {
                $times = explode('~', $param['i_incomTime']);
                $where[] = ['i.incomTime', 'between', $times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)->alias('i')
                ->join('purveyor p', 'p.id=i.punter_id', 'left')
                ->join('admin u', 'u.id=i.incom_user', 'left')
                ->where($where)
                ->field('i.*,p.name as pName,u.name as username')
                ->order('i.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            View::assign('typeList', $this->businessType);
            return view();
        }

    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $postData = $this->param;
            $mxid = $postData['mxid'] ?? [];
//            $locator=$postData['locator']??[];
            $warehouse_id = $postData['warehouse_id'] ?? [];
            $num = $postData['num'] ?? [];
            $material_id = $postData['material_id'] ?? [];
            $i_remark=$postData['i_remark']??[];
            $oCode=$postData['oCode']??'';
            $param = [
                'type' => $postData['type'],
                'incomTime' => $postData['incomTime'],
                'status' => $postData['status'],
                'oCode' => $postData['oCode'],
                'printCompany' => $postData['printCompany'],
                'punter_id' => $postData['punter_id'],
                'id' => $postData['id'] ?? 0,
            ];
            if (!$material_id) {
                return to_assign(1, '参数缺失');
            }

            Db::startTrans();
            $param['update_time'] = time();
            $id = $param['id'] ?? 0;
            try {
                if ($param['id'] > 0) {
                    $info=Db::name($this->table)->where('id',$id)->find();
                    $param['orderNum'] = $postData['orderNum']??'';
//                    if ($info['oCode']!=$oCode){
//                        $param['orderNum']=$this->getDJBHBuySql($this->table,'orderNum',$oCode);
//                    }

                    $whereDh[]=['status','>',-1];
                    $whereDh[]=['orderNum','=',$param['orderNum']];
                    if (isset($param['id'])&&$param['id']){
                        $whereDh[]=['id','<>',$param['id']];
                    }
                    if (Db::name($this->table)->where($whereDh)->value('orderNum')){
                        throw new Exception('单据编号已存在');
                    }
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $postData, $this->title);
                } else {
//                    $w_codeId=$warehouse_id[0]??1;
//                    $wCode=Db::name('warehouse')->where('id',$w_codeId)->value('wCode');
                    $ordernum=$this->getDJBHBuySql($this->table,'orderNum',$oCode);
                    $param['orderNum']=$ordernum;
                    $param['create_time'] = time();
                    $param['create_user'] = $this->uid;
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $postData, $this->title);
                }
                foreach ($material_id as $k => $v) {
                    if (empty($num[$k]) || empty($warehouse_id[$k])) {
                        throw new Exception('参数有误');
                    }
                    $mxData = [
                        'in_receipt_id' => $id,
                        'material_dossier_id' => $material_id[$k],
                        'num' => $num[$k],
                        'locator' => 1,
                        'warehouse_id' => $warehouse_id[$k],
                        'i_remark' => $i_remark[$k]??'',
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    if (isset($mxid[$k]) && $mxid[$k]) {
                        $mxData['id'] = $mxid[$k];
                    }
                    Db::name('in_receipt_detail')->save($mxData);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return to_assign(1, '操作失败:' . $e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=incom_user)username")->find();
                View::assign('detail', $detail);
                $mxList = InReceiptDetail::alias('ird')
                    ->join('material_dossier md', 'md.id=ird.material_dossier_id')
                    ->where('ird.in_receipt_id', $id)
                    ->where('ird.status', '>', -1)
                    ->with(['paket'])
                    ->field("md.bar_code,md.name,md.specs,md.brand,md.unit,ird.*")->select();
                View::assign('mxList', $mxList);
            }
            $punterList = Db::name('purveyor')->where('status', 1)->field('id,name')->select();
            $warehouseList = Db::name('warehouse')->where('status', 1)->field('id,name')->select();
            $printCompany=config('config.companyName');
            $orCode=config('config.oCode');
            View::assign('typeList', $this->businessType);
            View::assign('punterList', $punterList);
            View::assign('warehouseList', $warehouseList);
            View::assign('printCompany', $printCompany);
            View::assign('id', $id);
            View::assign('orCode', $orCode);
            View::assign('defalutTime', date('Y-m-d'));

            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $where[] = ['status', '=', 1];
            foreach (['bar_code', 'name', 'specs', 'brand'] as $v) {
                if (isset($this->param[$v]) && $this->param[$v]) {
                    $where[] = [$v, 'like', '%' . $this->param[$v] . '%'];
                }
            }
            $limit=$this->param['limit']??15;
            $list = \app\home\model\MaterialDossier::where($where)->with(['cangwei'])->paginate($limit);
            View::assign('list', $list);
            return table_assign(0, '', $list);
        } else {
            return \view('mx');
        }

    }

    public function removeMx()
    {
        $id = $this->param['id'];
        try {
            Db::name('in_receipt_detail')->where('id', $id)->update(['status' => -1, 'update_time' => time(), 'deleted' => time()]);
            add_log('add', $id, $this->param, $this->title);
        } catch (\Exception $e) {
            return to_assign(1, '删除失败:' . $e->getMessage());
        }
        return to_assign();
    }

    public function onSure()
    {

//        $ids=$this->param['id']??'';
//        $ids=explode(',',$ids);
//        $data=[];
//        foreach ($ids as $v){
//            $param=[
//                'id'=>$v
//            ];
////            $data[]=$res=InReceiptSever::doSure($this->param,2);
//            $data[]=$res=InReceiptSever::doSure($param,2);
//        }
//        return to_assign(1,'ok',$data);
                $res=InReceiptSever::doSure($this->param,$this->uid);
        return to_assign($res['code'],$res['msg'],$res['data']);
    }

    public function onCancel()
    {
        $id = $this->param['id'] ?? 0;
        if (!$id) {
            return to_assign(1, '参数缺失');
        }
        $status = Db::name($this->table)->where('id','in', $id)->where('status','=',1)->column('status');
        if ($status){
            return to_assign(1, '操作有误');
        }
        Db::startTrans();
        try {


         $thorderNum=Db::name($this->table)->where('type','in',['销售退货','采购收货'])
                        ->where('id','in',$id)
                        ->where('status','2')
                        ->column('orderNum');
            $mxStarus = Db::name('sale_hanging_bill')->where('status','>',1)->where('g_orderNum','in',$thorderNum)->column('status');
            if (!empty($mxStarus)){
                throw new Exception('单据已开始对账,无法撤回');
            }
            Db::name('sale_hanging_bill')
                ->where('status','>',-1)
                ->where('g_orderNum','in',$thorderNum)
                ->update(['status'=>-1,'deleted'=>time(),'update_time'=>time()]);

                Db::name($this->table)->where('id', $id)->update(['incom_user' => $this->uid, 'status' => 1, 'update_time' => time(), 'checkTime' => time()]);
                Db::name('in_receipt_detail')->where('status', '2')
                    ->where('in_receipt_id', $id)->update(['status' => 1, 'update_time' => time()]);
                add_log('back', $id, $this->param, $this->title);

        Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        return to_assign(1, '操作失败:' . $e->getMessage());
        }
        return to_assign(0, '操作成功');

}
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status = Db::name($this->table)->where('id', 'in', $id)->column('status');
            if (in_array('2', $status)) {
                return to_assign(1, "有已确认数据，不能删除");
            }
            Db::startTrans();
            try {
                Db::name($this->table)->where('id', 'in', $id)->update(['status' => -1, 'deleted' => time()]);
                Db::name('in_receipt_detail')->where('in_receipt_id', 'in', $id)->update(['status' => -1, 'deleted' => time()]);
                add_log('delete', $id, request()->param(), $this->title);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return to_assign(1, "删除失败" . $e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }


    public function importData()
    {
        try {
            if (!isset($_FILES['file'])) {
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $lgData = [];
                $types = [];
                $punids = [];
                $mcodes = [];
                $wids = [];
                $nums = [];
                $times = [];
                $orCodes=[];
                for ($j = 2; $j <= $highestRow; $j++) {
                    $type = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    $punter_id = (int)$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $mater_code = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $ware_house = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $num = (int)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                    $time = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $orCode=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                    $types[] = $type;
                    $punids[] = $punter_id;
                    $mcodes[] = $mater_code;
                    $wids[] = $ware_house?$ware_house:1;
                    $nums[] = $num;
                    $times[] = $time;
                    $orCodes[] = $orCode;
//
//                    if ($punter_id){
//                        $punter_id=Db::name('punter')->where('status',1)->where('id',$punter_id)->value('id');
//                        if (!$punter_id){
//                            $warText="第".($j-1) ."行填写有误";
//                            throw new Exception($warText);
//                        }
//                    }
//                    $ware_house=Db::name('warehouse')->where('id',$ware_house)->where('status',1)->value('id');
//                    if (!$ware_house){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
//
//                    $materInfo=Db::name('material_dossier')
//                        ->where('bar_code',$mater_code)
//                        ->where('status',1)
//                        ->find();
//
//                    if (!$num||!$materInfo){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
//
//                    $time=str_replace('/','-',$time);
//                    if (!$type){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
                    $lgData[]=[
                        "type" =>$type,
                        "incomTime" =>$time,
                        "punter_id" =>$punter_id,
                        'num'=>$num,
                        'bar_code'=>$mater_code,
                    ];
//                    $importData= [
//                        "type" =>$type,
//                        "punter_id" =>$punter_id,
//                        "incomTime" =>$time,
//                        'orderNum'=>orderNum('RKD'),
//                        "deleted" =>0,
//                        "create_time"=>time(),
//                        'update_time'=>time()
//                    ] ;
//                    $i_id= Db::name($this->table)->insertGetId($importData);
//                    $detail=[
//                        'in_receipt_id'=>$i_id,
//                        'num'=>$num,
//                        'warehouse_id'=>$ware_house,
//                        'locator'=>1,
//                        'material_dossier_id'=>$materInfo['id'],
//                        "create_time"=>time(),
//                        'update_time'=>time()
//                    ];
//                    Db::name('in_receipt_detail')->insert($detail);

                }

                $res = $this->createData($types, $punids, $mcodes, $wids, $nums, $times,$orCodes);
                if ($res['code']!=200){
                    throw new Exception($res['msg']);
                }

                $data=$res['data'];
                $importData=$data['importData'];
                $mxData=$data['mxData'];
                $i_id= Db::name($this->table)->insertGetId($importData);
                foreach ($mxData as &$m){
                    $m['in_receipt_id']=$i_id;
                }
                Db::name('in_receipt_detail')
                    ->insertAll($mxData);
                if ($lgData){
                    add_log('import', '', $lgData,$this->title);
                }

            }
        } catch (Exception $e) {
            add_log('import', '', $e->getMessage(), $this->title);
            return to_assign(1, '操作失败:' . $e->getMessage());
        }
        return to_assign();

    }

    public function printPage()
    {
        $id = $this->param['id'] ?? '';
        $printType=$this->param['printType']??1;
        $info = Db::name($this->table)->where('id', $id)
            ->field("*,(select name from fy_admin a where a.id=create_user) createName")
            ->find();
        $purInfo=Db::name('purveyor')->where('id',$info['punter_id'])->field('name,code')->find();
        if ($printType==1){
            $info['punterName']=$purInfo['code']??'';
        }elseif($printType==2){
            $info['punterName']=$purInfo['name']??'';
        }else{
            $pName=$purInfo['name']??'';
            $pCode=$purInfo['code']??'';
            $info['punterName']=$pName.' '.$pCode;
        }
        $mxList = InReceiptDetail::alias('ird')
            ->join('material_dossier md', 'md.id=ird.material_dossier_id', 'left')
            ->where('ird.in_receipt_id', $id)
            ->where('ird.status', '>', -1)
            ->field("md.bar_code,md.name,md.specs,md.unit,ird.*,
            (select name from fy_warehouse w where w.id=ird.warehouse_id)wName,
            (select name from fy_warehouse_detail wd where wd.id=ird.locator)locaName")
            ->order('ird.id ASC')
            ->select();

        $data = [
            'companyName' => $info['printCompany'],
            'orderType' => '入库单',
            'type' => $info['type'],
            'punterName' => $info['punterName']??'',
            'orderNum' => $info['orderNum'],
            'outTime' => $info['incomTime'],
            'printTime' => date('Y-m-d H:i:s'),
            'makeUser' => $info['createName'],
            'qz' => '',
            'shdw' => '',
            'pt' => '',
            'jy' => '',
            'sh' => '',
        ];
        $detail = [];
        foreach ($mxList as $k => $ml) {
            $detail[] = [
                'k' => $k + 1,
                'bar_code' => $ml['bar_code'],
                'name' => $ml['name'],
                'specs' => str_replace("'","’",$ml['specs']),
                'unit' => $ml['unit'],
                'wName' => $ml['wName'],
//                'locaName'=>$ml['locaName'],
                'num' => $ml['num'],
                'i_remark' => $ml['i_remark'],
            ];
        }
        $res = [];
        foreach ($detail as $key => $v) {
            $res[$key] = preg_replace("/\r|\n|\t/", "", $v);
//            $res[$key] = $v;
        }
        $data['detail'] = $res;
//        $temp = '{"panels":[{"index":0,"height":150,"width":220,"paperHeader":43.5,"paperFooter":425.19685039370086,"printElements":[{"options":{"left":126,"top":18,"height":21,"width":355.5,"field":"companyName","testData":"重庆洪湖摩托车配件制造有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center","showInPage":"first"},"printElementType":{"type":"text"}},{"options":{"left":253.5,"top":45,"height":13.5,"width":120,"field":"orderType","testData":"入库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":63,"height":9.75,"width":256.5,"title":"业务类型","field":"type","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":369,"top":63,"height":9.75,"width":228,"title":"单据编号","field":"orderNum","fontSize":12.75,"testData":"CKD100000008","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":369,"top":76.5,"height":15,"width":226.5,"title":"入库日期","field":"outTime","fontSize":12.75,"lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":78,"height":13.5,"width":340.5,"title":"送货单位","field":"punterName","fontSize":12.75,"testData":"重庆洪湖摩托车配件制造有限公司","lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":94.5,"height":48,"width":547.5,"field":"detail","fontSize":10.5,"fontFamily":"Microsoft YaHei","tableHeaderFontWeight":"500","tableBodyRowHeight":19.5,"columns":[[{"title":"序号","field":"k","width":38.90160867276421,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"物料编码","field":"bar_code","width":75.6779836594842,"colspan":1,"rowspan":1,"checked":true,"columnId":"bar_code"},{"title":"物料名称","field":"name","width":80.08116343721667,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"name"},{"title":"规格型号","field":"specs","width":190.19032087423847,"colspan":1,"rowspan":1,"checked":true,"columnId":"specs"},{"title":"单位","field":"unit","width":31.4968175846261,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"unit"},{"title":"数量","field":"num","width":53.66562121568592,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"num"},{"title":"备注","field":"i_remark","width":77.48648455598443,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"i_remark"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":271.5,"top":147,"height":9.75,"width":111,"title":"检验","field":"jy","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":391.5,"top":147,"height":9.75,"width":70.5,"title":"收货","field":"sh","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":157.5,"top":147,"height":9.75,"width":105,"title":"配套","field":"pt","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":468,"top":147,"height":9.75,"width":103.5,"title":"制单人","fontSize":12.75,"field":"makeUser","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":147,"height":9.75,"width":126,"title":"送货单位签字","field":"shdw","fontSize":12.75,"testData":"重庆洪","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":310.5,"top":370.5,"height":9.75,"width":114,"title":"蓝色客户","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":169.5,"top":370.5,"height":9.75,"width":114,"title":"红色财务","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":453,"top":370.5,"height":9.75,"width":112.5,"title":"黄色库房","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":370.5,"height":9.75,"width":115.5,"title":"白色留根","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}}],"paperNumberLeft":597,"paperNumberTop":366,"paperNumberDisabled":true,"orient":2}]}';
        $temp = '{"panels":[{"index":0,"height":150,"width":220,"paperHeader":91.5,"paperFooter":420,"printElements":[{"options":{"left":126,"top":18,"height":21,"width":355.5,"field":"companyName","testData":"重庆洪湖摩托车配件制造有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":253.5,"top":46.5,"height":13.5,"width":120,"field":"orderType","testData":"入库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":63,"height":9.75,"width":256.5,"title":"业务类型","field":"type","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":369,"top":63,"height":9.75,"width":228,"title":"单据编号","field":"orderNum","fontSize":12.75,"testData":"CKD100000008","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":369,"top":76.5,"height":15,"width":226.5,"title":"入库日期","field":"outTime","fontSize":12.75,"lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":78,"height":13.5,"width":340.5,"title":"送货单位","field":"punterName","fontSize":12.75,"testData":"重庆洪湖摩托车配件制造有限公司","lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":94.5,"height":40.5,"width":547.5,"field":"detail","fontSize":10.5,"fontFamily":"Microsoft YaHei","tableHeaderFontWeight":"500","columns":[[{"title":"序号","field":"k","width":38.90160867276421,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"物料编码","field":"bar_code","width":75.6779836594842,"colspan":1,"rowspan":1,"checked":true,"columnId":"bar_code"},{"title":"物料名称","field":"name","width":80.08116343721667,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"name"},{"title":"规格型号","field":"specs","width":190.19032087423847,"colspan":1,"rowspan":1,"checked":true,"columnId":"specs"},{"title":"单位","field":"unit","width":31.4968175846261,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"unit"},{"title":"数量","field":"num","width":53.66562121568592,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"num"},{"title":"备注","field":"i_remark","width":77.48648455598443,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"i_remark"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":271.5,"top":145.5,"height":9.75,"width":111,"title":"检验","field":"jy","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":391.5,"top":145.5,"height":9.75,"width":70.5,"title":"收货","field":"sh","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":157.5,"top":145.5,"height":9.75,"width":105,"title":"配套","field":"pt","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":468,"top":145.5,"height":9.75,"width":103.5,"title":"制单人","fontSize":12.75,"field":"makeUser","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":145.5,"height":9.75,"width":126,"title":"送货单位签字","field":"shdw","fontSize":12.75,"testData":"重庆洪","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":312,"top":169.5,"height":9.75,"width":114,"title":"蓝色客户","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":168,"top":169.5,"height":9.75,"width":114,"title":"红色财务","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":453,"top":169.5,"height":9.75,"width":112.5,"title":"黄色库房","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":169.5,"height":9.75,"width":115.5,"title":"白色留根","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}}],"paperNumberLeft":582,"paperNumberTop":391.5,"paperNumberDisabled":true,"orient":2}]}';
        View::assign('temp', $temp);
        View::assign('info', json_encode($data, 320));
        return \view();
    }

    public function createData($types, $punids, $mcodes, $wids, $nums, $times,$orCodes)
    {
        $type1 = array_unique($types);
        $punids1 = array_unique($punids);
        $wids1 = array_unique($wids);
        $times1 = array_unique($times);
        $orCodes1 = array_unique($orCodes);
//        if (count($type1) != 1 ||count($wids1) != 1 || count($times1) != 1) {
//            return ['code' => 400, 'msg' => '数据填写不一致1'];
//        }
       if (count($type1) != 1 ||count($orCodes1) != 1 ||count($wids1) != 1 || count($times1) != 1) {
            return ['code' => 400, 'msg' => '数据填写不一致1'];
        }

        if (isset($punids1[0])&&$punids1[0]) {
            $punter_id = Db::name('purveyor')->where('status', 1)->where('id', $punids1[0])->value('id');
            if (!$punter_id) {
                return ['code' => 400, 'msg' => '数据填写有误'];
            }
        }


        $time = str_replace('/', '-', $times1[0]);
        if (!$time) {
            return ['code' => 400, 'msg' => '数据填写有误'];
        }
//        $wCode=Db::name('warehouse')->where('id',$wids1[0])->value('wCode');
        $importData = [
            "type" => $type1[0],
            "punter_id" => $punids1[0]??0,
            "create_user" => $this->uid,
            "oCode" => $orCodes1[0],
            "incomTime" => $times1[0],
            'orderNum' => $this->getDJBHBuySql($this->table,'orderNum',$orCodes1[0]),
            "deleted" => 0,
            "create_time" => time(),
            'update_time' => time()
        ];
        $mx1 = [];
        foreach ($mcodes as $k => $w) {
            if (!$nums[$k]){
                return ['code' => 400, 'msg' => '数据填写有误'];
                break;
            }
            $materInfo = Db::name('material_dossier')
                ->where('bar_code', $mcodes[$k])
                ->where('status', 1)
                ->find();

            if (!$materInfo) {
                return ['code' => 400, 'msg' => '物料不存在'];
            }
            if (isset($mx1['wid_' . $materInfo['id']])) {
                $mx1['wid_' . $materInfo['id']] += $nums[$k];
            } else {
                $mx1['wid_' . $materInfo['id']] = $nums[$k];
            }
        }
        $mxData = [];
        foreach ($mx1 as $key => $m1) {
            $str = explode('_', $key);
            $mxData[] = [
                'num' => $m1,
                'warehouse_id' => $wids1[0]??1,
                'material_dossier_id' => $str[1],
                "create_time" => time(),
                'update_time' => time()
            ];
        }
        return ['code'=>200,'msg'=>'','data'=>['importData'=>$importData,'mxData'=>$mxData]];
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)->alias('i')
            ->join('purveyor p', 'p.id=i.punter_id', 'left')
            ->join('admin u', 'u.id=i.incom_user', 'left')
            ->where($where)
            ->field('i.*,p.name as pName,u.name as username')
            ->order('i.id DESC')->select()->each(function ($item){
                $item['status']=$item['status']==1?'草稿':'已确认';
                return $item;
            });
        $title = [
            'id' => 'ID',
            'orderNum' => '单据编号',
            'type' => '业务类型',
            'pName' => '送货单位',
            'username' => '入库人',
            'incomTime' => '入库时间',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }


}